import {designComponent, onMounted, PropType, useModel, useRefs} from "plain-design-composition";
import React from "react";
import './monaco-editor.css'
import * as monaco from 'monaco-editor';
import {editor, IKeyboardEvent} from "monaco-editor";
import IStandaloneCodeEditor = editor.IStandaloneCodeEditor;

export const MonacaEditor = designComponent({
    props: {
        modelValue: {type: String},
        language: {type: String as PropType<'javascript' | 'css' | 'html' | 'typescript'|'markdown'>, required: true},
        theme: {type: String as PropType<'vs' | 'vs-dark' | 'hc-black'>, default: 'vs'},
    },
    emits: {
        onUpdateModelValue: () => true,
        onKeydown: (e: IKeyboardEvent) => true,
    },
    setup({props, event: {emit}}) {

        let ins: IStandaloneCodeEditor;

        const model = useModel(() => props.modelValue, emit.onUpdateModelValue, {
            onChange: val => {
                !!ins && ins.setValue(val || '')
            }
        })
        const {refs, onRef} = useRefs({el: HTMLDivElement})

        onMounted(() => {
            ins = monaco.editor.create(refs.el!, {
                value: model.value,
                language: props.language,
                theme: props.theme,
            });

            ins.onDidChangeModelContent(() => {
                model.value = ins.getValue()
            })

            ins.onKeyDown(emit.onKeydown)

            return () => {
                ins.dispose()
            }
        })

        return () => (
            <div ref={onRef.el} className="o2-monaco-editor"/>
        )
    },
})
